package com.wbdgj.ui.login;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.internal.LinkedTreeMap;
import com.igexin.sdk.PushManager;
import com.tencent.connect.common.Constants;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.tauth.Tencent;
import com.wbdgj.R;
import com.wbdgj.base.BaseActivity;
import com.wbdgj.base.BaseApplication;
import com.wbdgj.base.BaseUiListener;
import com.wbdgj.http.HttpAdapter;
import com.wbdgj.http.HttpVersionAdapter;
import com.wbdgj.http.OnNoResponseListener;
import com.wbdgj.http.OnResponseListener;
import com.wbdgj.model.ResultObjectModel;
import com.wbdgj.model.ResultRefeshModel;
import com.wbdgj.model.ResultVersionModel;
import com.wbdgj.ui.MainActivity;
import com.wbdgj.ui.UpdateDialogActivity;
import com.wbdgj.ui.mine.QqPhoneActivity;
import com.wbdgj.utils.LogUtils;
import com.wbdgj.utils.SpKeyUtils;
import com.wbdgj.utils.ToastUtils;

import org.json.JSONObject;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;

;

/**
 * Created by Administrator on 2017/9/21.
 */

public class LoginAuthActivity extends BaseActivity{



    @BindView(R.id.login_phone_et)
    public EditText etPhone;

    @BindView(R.id.login_psw_et)
    public EditText etPsw;


    @BindView(R.id.hqyzm)
    TextView hqyzm;
    final int totalCount = 60;
    int time = 1;


    private final int SDK_PERMISSION_REQUEST = 127;
    private Context context = this;
    SharedPreferences sharedPreferences;
    private String versionCode;
    private static final int REQUEST_PERMISSION = 0;
    private String cid;
    private boolean isClick = false;

    private Tencent mTencent;
    private String QQAppID = "101529516";
    private String Scope = "get_user_info,add_t,qrcode";
    private BaseUiListener listener;
    private IWXAPI mIwxapi;
    private String wechatAppID = "wxf1069c4f961f956e";

    @Override
    protected int getLayoutResId() {
        return R.layout.ui_login_auth;
    }

    @Override
    protected void initView() {
        cid = PushManager.getInstance().getClientid(this);
        BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.CID, cid);
        Log.e("zp","cid="+ PushManager.getInstance().getClientid(this));
        getPersimmions();
        sharedPreferences = getSharedPreferences("userInfo", 0);
        etPhone.setText(BaseApplication.getInstance().getSpUtil().getString(SpKeyUtils.LOGIN_PHONE));
        isUpdate();

        // 获取IWXAPI 实例
        mIwxapi = WXAPIFactory.createWXAPI(context, wechatAppID, false);
        // 将应用的APPID 注册到微信
        mIwxapi.registerApp(wechatAppID);

        mTencent = Tencent.createInstance(QQAppID, context);
        listener = new BaseUiListener() {
            @Override
            protected void doComplete(JSONObject values) {
                super.doComplete(values);
                Gson gson = new Gson();
                JsonObject jsonObject  = gson.fromJson(values+"", JsonObject.class);
                qq( String.valueOf(jsonObject.get("openid")).replace("\"", ""));
            }
        };
    }

    private void requestPermission() {
        ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE, Manifest.permission.ACCESS_FINE_LOCATION},
                REQUEST_PERMISSION);
    }

    @OnClick(value = {R.id.wjmm, R.id.wxLay, R.id.qqLay, R.id.authLogin,R.id.register, R.id.login_btn, R.id.forget })
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.wjmm:
                launch(FindPsswordActivity.class);
                break;
            case R.id.wxLay:
                BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.WXFROM, "1");
                SendAuth.Req req = new SendAuth.Req();
                req.scope = "snsapi_userinfo";
                req.state = "wechat_sdk_test";
                mIwxapi.sendReq(req);
                break;
            case R.id.qqLay:
                mTencent.login(LoginAuthActivity.this, Scope, listener);
                break;
            case R.id.authLogin:
                finish();
                break;
            case R.id.login_btn:
                if (ContextCompat.checkSelfPermission(context,
                        Manifest.permission.ACCESS_FINE_LOCATION)
                        != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 10);
                    ToastUtils.toastShort("请打开应用定位权限!");
                    return;
                }

                if (TextUtils.isEmpty(etPhone.getText().toString())) {
                    showToast("登陆号码不能为空");
                    return;
                }
                if (TextUtils.isEmpty(etPsw.getText().toString())) {
                    showToast("验证码不能为空");
                    return;
                }
                login();

                break;

            case R.id.register:
                launch(RegisterActivity.class);
                break;
            case R.id.forget:
                if (isClick){
                    ToastUtils.toastShort("请稍后再点！");
                    return;
                }
                if (TextUtils.isEmpty(etPhone.getText().toString())){
                    ToastUtils.toastShort("手机号不能为空！");
                    return;
                }
                userscode();
                break;
            default:
                break;
        }
    }

    private void userscode() {
        Call<ResultObjectModel> call = HttpAdapter.getSerives().queryAuth(etPhone.getText().toString());
        call.enqueue(new OnResponseListener<ResultObjectModel>(this) {
            @Override
            protected void onSuccess(ResultObjectModel userModelBaseResultModel) {
                if(userModelBaseResultModel.getResultCode().equals("0000")){
                    ToastUtils.toastShort(userModelBaseResultModel.getResultMsg());
                    isClick = true;
                    time = 1;
                    startCount();
                }else{
                    ToastUtils.toastShort(userModelBaseResultModel.getResultMsg());
                }
            }
        });
    }

    private void startCount() {
        getWindow().getDecorView().postDelayed(runnable, 1000);
    }

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            hqyzm.setText(String.valueOf(String.valueOf(totalCount - time))+"秒后重新发送");
            hqyzm.setTextColor(getResources().getColor(R.color.red));
            time++;
            if (time > totalCount) {
                next();
            } else {
                startCount();
            }
        }
    };

    private void next() {
        isClick = false;
        hqyzm.setText("点击获取");
        hqyzm.setTextColor(getResources().getColor(R.color.colorPrimary));
    }

    private void login() {
        Call<ResultObjectModel> call = HttpAdapter.getSerives().loginByAuth(etPhone.getText().toString(), etPsw.getText().toString(), "android"+versionCode);
        call.enqueue(new OnResponseListener<ResultObjectModel>(this) {
            @Override
            protected void onSuccess(ResultObjectModel userModelBaseResultModel) {
                if(userModelBaseResultModel.getResultCode().equals("0000")){
                    PushManager.getInstance().bindAlias(context, etPhone.getText().toString(), cid);
                    LinkedTreeMap linkedTreeMap = (LinkedTreeMap) userModelBaseResultModel.getData();
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.TOKEN, linkedTreeMap.get("TOKEN")+"");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.IS_AUTO_LOGIN, "1");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.LOGIN_PHONE, etPhone.getText().toString());
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.LOGIN_PSW, "");
                    if (linkedTreeMap.containsKey("NAME")){
                        if ((linkedTreeMap.get("NAME")+"").equals("")){
                            Intent intent = new Intent(context, MainActivity.class);
                            intent.putExtra("sm", 1);
                            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                        }else{
                            Intent intent = new Intent(context, MainActivity.class);
                            intent.putExtra("sm", 0);
                            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                        }
                    }else{
                        Intent intent = new Intent(context, MainActivity.class);
                        intent.putExtra("sm", 1);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                    }

                }else{
                    ToastUtils.toastShort(userModelBaseResultModel.getResultMsg());
                }
            }

            @Override
            protected void onFailure(int code) {
                super.onFailure(code);
                Log.e("zp", "code="+code);
            }
        });
    }

    /**
     * 判断是否有更新
     */
    private void isUpdate() {

        PackageManager packageManager = context.getPackageManager();
        PackageInfo packageInfo = null;
        try {
            packageInfo = packageManager.getPackageInfo(
                    context.getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        versionCode = packageInfo.versionName;
        Call<ResultRefeshModel<ResultVersionModel>> call = HttpVersionAdapter.getSerives().version();
        call.enqueue(new OnNoResponseListener<ResultRefeshModel<ResultVersionModel>>(context) {
            @Override
            protected void onSuccess(final ResultRefeshModel<ResultVersionModel> followModelBaseResultModel) {
                if (followModelBaseResultModel.getCode() == 0){
                    LogUtils.loge("appVersion="+versionCode);
                    double version01 = Double.parseDouble(versionCode);
                    double version02 = Double.parseDouble(followModelBaseResultModel.getData().getBuildVersion());
                    if(version02>version01){
                        startActivity(new Intent(context, UpdateDialogActivity.class).putExtra("content", followModelBaseResultModel.getData().getBuildUpdateDescription()).putExtra("url", followModelBaseResultModel.getData().getDownloadURL()));
//                        final ConfirmDialog confirmDialog = new ConfirmDialog(context, "有最新的版本发布，确定更新吗？", 1);
//                        confirmDialog.show();
//                        confirmDialog.setCanceledOnTouchOutside(false);
//                        confirmDialog.setClicklistener(new ConfirmDialog.ClickListenerInterface() {
//                            @Override
//                            public void doConfirm() {
//                                confirmDialog.dismiss();
//                                Intent intent = new Intent();
//                                intent.setAction("android.intent.action.VIEW");
//                                Uri content_url = Uri.parse(followModelBaseResultModel.getData().getDownloadURL());
//                                intent.setData(content_url);
//                                startActivity(intent);
//                            }
//
//                            @Override
//                            public void doCancel() {
//                                confirmDialog.dismiss();
//                            }
//                        });

                    }
                }


            }

            @Override
            protected void onFailure(String msg) {
                super.onFailure(msg);
            }
        });

    }

    @TargetApi(23)
    private void getPersimmions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ArrayList<String> permissions = new ArrayList<String>();
//            if (addPermission(permissions, Manifest.permission.READ_PHONE_STATE)) {
//                permissions.add(Manifest.permission.READ_PHONE_STATE);
//            }
//            if (addPermission(permissions, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
//                permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
//            }
            if (addPermission(permissions, Manifest.permission.ACCESS_FINE_LOCATION)) {
                permissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
            }

            if (permissions.size() > 0) {
                requestPermissions(permissions.toArray(new String[permissions.size()]), SDK_PERMISSION_REQUEST);
            }
        }
    }

    @TargetApi(23)
    private boolean addPermission(ArrayList<String> permissionsList, String permission) {
        if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) { // 如果应用没有获得对应权限,则添加到列表中,准备批量申请
            if (shouldShowRequestPermissionRationale(permission)){
                return true;
            }else{
                permissionsList.add(permission);
                return false;
            }

        }else{
            return true;
        }
    }

    @TargetApi(23)
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        // TODO Auto-generated method stub
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == Constants.REQUEST_LOGIN) {
            Tencent.onActivityResultData(requestCode, resultCode, data, listener);
            Log.e("zp", "resultCode="+resultCode);
        }
    }

    private void qq(final String opid) {
        Call<ResultObjectModel> call = HttpAdapter.getSerives().qq(opid);
        call.enqueue(new OnNoResponseListener<ResultObjectModel>(context) {
            @Override
            protected void onSuccess(ResultObjectModel userModelBaseResultModel) {
                if(userModelBaseResultModel.getResultCode().equals("0000")){
                    ToastUtils.toastShort(userModelBaseResultModel.getResultMsg());
                    LinkedTreeMap linkedTreeMap = (LinkedTreeMap) userModelBaseResultModel.getData();
                    PushManager.getInstance().bindAlias(context, linkedTreeMap.get("PHONE")+"", cid);

                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.TOKEN, linkedTreeMap.get("TOKEN")+"");
                    BaseApplication.getInstance().getSpUtil().putString(SpKeyUtils.IS_AUTO_LOGIN, "1");
                    if (linkedTreeMap.containsKey("NAME")){
                        if ((linkedTreeMap.get("NAME")+"").equals("")){
                            Intent intent = new Intent(context, MainActivity.class);
                            intent.putExtra("sm", 1);
                            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                        }else{
                            Intent intent = new Intent(context, MainActivity.class);
                            intent.putExtra("sm", 0);
                            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                        }
                    }else{
                        Intent intent = new Intent(context, MainActivity.class);
                        intent.putExtra("sm", 1);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                    }
                }else if(userModelBaseResultModel.getResultCode().equals("7777")){
                    startActivity(new Intent(context, QqPhoneActivity.class).putExtra("openId", opid));
                }
            }
        });
    }
}
